<template>
  <a-tree-select
    allowClear
    labelInValue
    :getPopupContainer="(node) => node.parentNode"
    style="width: 100%"
    :disabled="disabled"
    :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
    :placeholder="placeholder"
    :loadData="asyncLoadTreeData"
    :value="treeValue"
    :treeData="treeData"
    :multiple="multiple"
    @change="onChange"
    @search="onSearch">
  </a-tree-select>
</template>
<script>

  /**
   * 通过现成的JSON数据 加载一个树控件
   * 不需要是树结构 会自动通过父节点生成JSON树
   */
  export default {
    name: 'JTreeSelectLazy',
    props: {
      value:{
        type: String,
        required: false
      },
      placeholder:{
        type: String,
        default: '请选择',
        required: false
      },
      dict:{
        type: String,
        default: '',
        required: false
      },
      pidField:{
        type: String,
        default: 'pid',
        required: false
      },
      pidValue:{
        type: String,
        default: '',
        required: false
      },
      disabled:{
        type:Boolean,
        default:false,
        required:false
      },
      hasChildField:{
        type: String,
        default: '',
        required: false
      },
      condition:{
        type:String,
        default:'',
        required:false
      },
      // 是否支持多选
      multiple: {
        type: Boolean,
        default: false,
      },
      loadTriggleChange:{
        type: Boolean,
        default: false,
        required:false
      },
      nodeData:{
        type: Array,
        default: [],
        required:false
      }
    },
    data () {
      return {
        treeValue: null,
        treeData:[],
        tableName:"",
        text:"",
        code:""
      }
    },
    watch: {
      value () {
        this.loadItemByCode()
      },
      dict(){
        this.initDictInfo()
        this.loadRoot();
      }
    },
    created(){
      this.validateProp().then(()=>{
        this.initDictInfo()
        this.loadRoot()
        this.loadItemByCode()
      })
    },
    methods: {
      loadItemByCode(){
        if(!this.value || this.value=="0"){
          this.treeValue = null
        }else{
          var that = this;
          let values = this.value.split(',')
          this.treeValue = [];
          this.nodeData.forEach(function(item) {
            for (let index in values) {
              values[index] === item.value && that.treeValue.push({
                key: item.value,
                value: item.value,
                label: item.label
              });
            }
          })
          if (this.treeValue.length > 0) {
            this.onLoadTriggleChange(this.treeValue[0].label);
          }
        }
      },
      onLoadTriggleChange(text){
        //只有单选才会触发
        if(!this.multiple && this.loadTriggleChange){
          this.$emit('change', this.value, text)
        }
      },
      initDictInfo(){
        if (this.nodeData) {
          this.treeData = this.toTree(this.nodeData, this.pidValue);
        }
      },
      toTree (data, parentId) {
        let that = this;
        let itemArr = [];
        data.forEach(function(item) {
          let pidField = item[that.pidField];
          if (pidField == parentId) {
            item.children = that.toTree(data, item.id);
            itemArr.push(item);
          }
        })
        return itemArr;
      },
      asyncLoadTreeData (treeNode) {
        return new Promise((resolve) => {
          resolve()
        })
      },
      addChildren(pid,children,treeArray){

      },
      loadRoot(){

      },
      onChange(value){
        if (!value) {
          this.$emit('change', '');
          this.treeValue = null
        } else {
          // 通过selectable属性判断该节点是否可点击
          this.nodeData.forEach(function(item) {
            if (item.value === value.value && !item.selectable) {
              return;
            }
          })
          if (value instanceof Array) {
            this.$emit('change', value.map(item => item.value).join(','))
            this.treeValue = value
          } else {
            this.$emit('change', value.value,value.label)
            this.treeValue = value
          }
        }
      },
      onSearch(value){
        console.log(value)
      },
      getCurrTreeData(){
        return this.treeData
      },
      validateProp(){
        let mycondition = this.condition
        return new Promise((resolve,reject)=>{
          if(!mycondition){
            resolve();
          }else{
            try {
              let test=JSON.parse(mycondition);
              if(typeof test == 'object' && test){
                resolve()
              }else{
                this.$message.error("组件JTreeSelectLazy-condition传值有误，需要一个json字符串!")
                reject()
              }
            } catch(e) {
              this.$message.error("组件JTreeSelectLazy-condition传值有误，需要一个json字符串!")
              reject()
            }
          }
        })
      }
    },
    //2.2新增 在组件内定义 指定父组件调用时候的传值属性和事件类型 这个牛逼
    model: {
      prop: 'value',
      event: 'change'
    }
  }
</script>
